/*
 * Copyright (C) 2014 Evgeniy Egorov
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ru.apertum.qsystem.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * Выключить сервер консольной командой послав exit.
 *
 * @author Evgeniy Egorov
 */
public class Exit {

    /**
     * Выключить сервер консольной командой послав exit.
     */
    public static void main(String[] args) throws IOException {
        sendExit(args.length > 2 ? args[2] : "exit",
                args.length > 0 && !isInt(args[0]) ? args[0] : "127.0.0.1",
                args.length > 0 && isInt(args[0]) ? Integer.parseInt(args[0]) : (args.length > 1 && isInt(args[1]) ? Integer.parseInt(args[1]) : 3128));
    }

    private static boolean isInt(String str) {
        return str.matches("^-?\\d+$");
    }

    /**
     * Отослать команду на адрес и порт.
     *
     * @param cmd     команда.
     * @param address адрес.
     * @param port    порт.
     */
    public static void sendExit(String cmd, String address, int port) throws IOException {
        System.out.println("cmd=" + cmd + " address=" + address + " port=" + port);
        try (final Socket socket = new Socket()) {
            socket.setTcpNoDelay(true);
            socket.connect(new InetSocketAddress(address, port), 3000);
            socket.getOutputStream().write(cmd.getBytes(StandardCharsets.UTF_8));
            Thread.sleep(500);
            System.out.println("Exit finished.");
        } catch (Exception ex) {
            System.err.println("ERROR: " + ex.getLocalizedMessage());
        }
    }
}
